<template>
  <view class="page">
    <uv-navbar
      title="查找设备"
      placeholder
      bg-color="#fff"
      auto-back
      left-icon-color="#757575"
      title-style="color: #000000; font-size: 32rpx"
    >
      <template #right>
        <uv-text text="确定" color="#4EA770" size="30rpx" @click="handleConfirm" />
      </template>
    </uv-navbar>
    <uv-sticky :offset-top="offsetTop" bg-color="#fff">
      <uv-search
        v-model="searchText"
        show-action
        clearabled
        margin="20rpx"
        placeholder="搜索"
        action-text="取消"
        :animation="searchText ? false : true"
        @search="handleSearch"
        @clear="handleSearch"
        @custom="handleCancel"
      />
    </uv-sticky>
    <uv-radio-group v-model="selectIndex">
      <view class="device-item" v-for="(i, index) in dataList" :key="index">
        <uv-radio
          :name="index"
          :custom-style="{
            margin: '14rpx',
            padding: '6rpx',
          }"
          active-color="#4ea770"
        >
          {{ i.deviceName }} {{ i.floorDescribe }} {{ i.remainCount }}
        </uv-radio>
      </view>
    </uv-radio-group>
  </view>
</template>
<script setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { findDevice } from "@/request/task.js";

const searchText = ref(); // 搜索框内容
const subPlanId = ref(""); // 任务ID
const deviceId = ref(); // 设备ID
const dataList = ref([]); // 数据列表
const selectIndex = ref({}); // 选中设备下标

const offsetTop = computed(() => {
  let statusHeight = uni.getSystemInfoSync().statusBarHeight;
  // #ifdef APP-PLUS
  statusHeight = statusHeight + 44;
  // #endif
  return statusHeight;
});

onLoad((e) => {
  subPlanId.value = e.subPlanId;
  deviceId.value = e.deviceId;
  getList();
});

// 搜索
const handleSearch = (value = null) => {
  searchText.value = value;
  deviceId.value = null;
  getList();
};

// 取消搜索
const handleCancel = () => {
  searchText.value = null;
  handleSearch();
};

// 获取列表
const getList = () => {
  let data = {
    subPlanId: subPlanId.value,
    deviceId: deviceId.value,
    deviceName: searchText.value,
  };
  findDevice(data).then((res) => {
    if (res.code == 200) {
      dataList.value = res.data;
    }
  });
};

// 确认选中设备
const handleConfirm = () => {
  console.log(selectIndex.value);
  let row = dataList.value[selectIndex.value];
  uni.setStorageSync("device-C", JSON.stringify(row));
  uni.navigateBack({
    delta: 1,
  });
};
</script>
<style lang="scss" scoped>
@import "@/uni.scss";
.page {
  min-height: 100vh;
  background: #f9f9f9;
  box-sizing: border-box;
  padding-bottom: 20rpx;
  .device-item {
    width: 100%;
    font-size: 28rpx;
    border: 2rpx solid #dedede;
    background-color: #fff;
    margin: 10rpx 20rpx;
    border-radius: 8rpx;
    overflow: hidden;
    position: relative;
    text {
      position: inherit;
      z-index: 2;
      color: #757575;
    }
  }
}
</style>
